async function deleteMedia(params) {
  const { mediaIds = [], deleteOriginalFile = true } = params;
  const db = uniCloud.database();

  if (mediaIds.length <= 0) {
    return {
      errCode: 0,
    };
  }

  const mediaList = await db
    .collection("uni-media-library")
    .where({
      _id: db.command.in(mediaIds),
    })
    .get();

  if (!mediaList.data || mediaList.data.length <= 0) {
    return {
      errCode: 0,
    };
  }

  const mediaFileIds = mediaList.data
    .filter((item) => item.src)
    .map((item) => item.src);
  const coverFileIds = mediaList.data
    .filter((item) => item.type === "video" && item.cover)
    .map((item) => item.cover);

  // 内部辅助函数：deleteImage
  async function deleteImage(id) {
    try {
      // 统一处理为数组形式
      const ids = Array.isArray(id) ? id : [id];

      // 分离七牛云和阿里云的文件ID
      const qiniuFiles = [];
      const aliFiles = [];

      ids.forEach((fileId) => {
        if (fileId.startsWith("qiniu://")) {
          qiniuFiles.push(fileId);
        } else if (fileId.startsWith("cloud://")) {
          aliFiles.push(fileId);
        } else {
          console.warn("未知文件ID格式，跳过:", fileId);
        }
      });

      if (qiniuFiles.length > 0) {
        const extStorageManager = uniCloud.getExtStorageManager({
          provider: "qiniu",
          domain: "cdn.isscloud.site",
        });
        const res = await extStorageManager.deleteFile({ fileList: qiniuFiles });
        console.log("deleteFile_res", res);
      }

      if (aliFiles.length > 0) {
        const res2 = await uniCloud.deleteFile({ fileList: aliFiles });
      }
    } catch (e) {
      console.error("图片删除失败:", e);
      throw e; // 抛出错误由外层捕获
    }
  }

  try {
    // 删除媒体文件
    if (deleteOriginalFile && mediaFileIds.length) {
      await deleteImage(mediaFileIds);
    }
    // 删除封面文件（如果是视频）
    if (deleteOriginalFile && coverFileIds.length) {
      await deleteImage(coverFileIds);
    }
    // 删除数据库记录
    await db
      .collection("uni-media-library")
      .where({
        _id: db.command.in(mediaIds),
      })
      .remove();
  } catch (e) {
    console.log("删除云存储图片失败", e);
    return {
      errCode: 500,
      errMsg: "删除失败: " + e.message,
    };
  }

  return {
    errCode: 0,
  };
}

module.exports = deleteMedia;